package cn.org.dian.easycommunicate.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import cn.org.dian.easycommunicate.ConfigActivity;
import cn.org.dian.easycommunicate.R;

import com.google.api.translate.Language;

public class Utilities {

    private static ConnectivityManager connMan = null;
    
    private static SharedPreferences sharedPreferences = null;
    
    private static AssetManager assetManager = null;
    
    private static final String TAG = "Utilities";
    
    private static String currentLanguage = null; 
    private static final String LANGUAGE_ENGLISH = "en";
    private static final String LANGYAGE_CHINESE = "zh";
    
    // private static final String ASSET_BASE_PATH = "file:///android_asset/audio_files";
    
    public static void init(Activity activity) {
        Utilities.connMan = (ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        Utilities.sharedPreferences = activity.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
        Utilities.assetManager = activity.getAssets();
        currentLanguage = Locale.getDefault().getLanguage();
        Log.d(TAG, "currentLanguage: " + currentLanguage);
    }
    
    public static boolean playLocalFile(Language language, String speakText) {
        String localFileName = language.toString() + "_" + 
                                BKDRHash(speakText).toString() + ".mp3";
        AssetFileDescriptor afd = null;
        try {
            afd = assetManager.openFd("audio_files/" + localFileName);
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, "local file not found for: " +language.toString()+" " +speakText );
            return false;
        }
        
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepare();
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
            return false;
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
            return false;
        } catch (IOException e1) {
            e1.printStackTrace();
            return false;
        }
        mediaPlayer.start();
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();
                mp = null;
            }
        });
        return true;
    }
    
    
    private static Integer BKDRHash(String str) {
        int seed = 131; // 31 131 1313 13131 131313 etc..
        int hash = 0;

        for (int i = 0; i < str.length(); i++) {
            hash = (hash * seed) + str.charAt(i);
        }

        return (hash & 0x7FFFFFFF);
    }
    
    
    public static String utf8Encode(String raw) {
        try {
            return URLEncoder.encode(raw, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static String convertToLegalName(String origin) {
        return utf8Encode(origin);
    }
    
    
    public static boolean checkNetworkUsability() {
        NetworkInfo networkInfo = connMan.getActiveNetworkInfo();
        if (null != networkInfo && networkInfo.isConnectedOrConnecting()) {
            return true;
        } else {
            return false;
        }
    }
    
    public static boolean checkSDCardUsability() {
        String externalStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(externalStorageState)) {
            return true;
        } else {
            return false;
        }
    }
    
    // for menu
    public static boolean onCreateOptionsMenu(Activity activity, Menu menu) {
        MenuInflater inflater = activity.getMenuInflater();
        inflater.inflate(R.menu.main_frame_option_menu, menu);
        return true;
    }
    
    public static boolean onOptionsItemSelected(Activity activity, MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_settings:
            activity.startActivity(new Intent(activity, ConfigActivity.class));
            return true;
        case R.id.menu_help:
        	showHelpDialog(activity);
            return true;

        case R.id.menu_search:
            activity.onSearchRequested();
            
        default:
            return true;
        }
    }
    
    
    //
    //  for Toast
    //
    
    public static void showShortToast(Context context, int resId) {
        Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }
    
    public static void showLongToast(Context context, int resId) {
        Toast.makeText(context, resId, Toast.LENGTH_LONG).show();
    }
    
    public static void showShortToast(Context context, String string) {
        Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
    }
    
    public static void showLongToast(Context context, String string) {
        Toast.makeText(context, string, Toast.LENGTH_LONG).show();
    }

    public static ConnectivityManager getConnectivityManager() {
        return connMan;
    }

    public static SharedPreferences getSharedPreferences() {
        return sharedPreferences;
    }
    
    
    public static boolean isCurrentLanEng() {
		return currentLanguage.equalsIgnoreCase(LANGUAGE_ENGLISH);
	}
    
    private static void showHelpDialog(Activity activity) {
    	AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    	builder.setTitle(R.string.help)
    		.setMessage(activity.getText(R.string.help_content))
    		.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
					
				}
			});
		builder.create().show();
	}
}
